// pages/newAddress/newAddress.js
// 省市区信息
import { areaList } from '../../utils/area.js';
// 弹框提示
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
// 确认框
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
// api请求
import { changeAddress,deleteAddress,getLocation } from "../../api/user.js";

Page({
  data: {
    id:'', //当前地址ID
    username:'',//姓名
    phone:'',//电话号码
    areaList,
    show:false,//地址弹出层显示隐藏
    region:'', //选择的当前地址
    historAddres:'',//记录选择的地址 如：140405
    detailedAddres:'', //详细地址
    checked: true, //是否为默认地址
    phoneErr:'', //电话格式错误提示信息
    isCorrect:true, //电话格式是否正确
  },

  // 获取地理位置信息
  getPositioning() {
    wx.getLocation({
      type: 'wgs84',
      altitude: true,
      isHighAccuracy: true,
      success: (res) => {
        // console.log(res);
        let { latitude,longitude } = res;
        this.getCity(latitude,longitude);
      },
      fail: (err) => {
        wx.openSetting({
          withSubscriptions: true,
          success: (res) => {
            let isSuthSetting = res.authSetting
            res.authSetting = {
              "scope.userInfo": true,
              "scope.userLocation": true
            }
           if(isSuthSetting["scope.userLocation"]) {
            //  用户允许就再调用一次自己
              this.getPositioning();
           }else{
              // console.log('没授权');
           }
          }
        })
      }
    })
  },

    // 获取位置
    async getCity(latitude, longitude) {
      let {
        result
      } = await getLocation(latitude, longitude);
      let {adcode,province,city,district} = result.addressComponent;
      this.setData({
        historAddres:adcode,
        region:`${province}/${city}/${district}`,
        detailedAddres:result.sematic_description
      })
    },

  // 手机号输入时触发
  phoneInput(e) {
    let isErr = e.detail.search(/^1[356789]\d{9}$/)
    isErr = isErr == -1? '请输入正确号码格式' : '';
    let isCorrect = isErr == ''? true : false;
    this.setData({
      phoneErr:isErr,
      isCorrect
    })
  },

  // 地址选择
  clickInput() {
    this.setData({
      show:true
    })
  },

  // 地址选择点击右上角完成按钮
  confirm(e) {
    let addresArr = e.detail.values;
    let addres = addresArr.map(item=>item.name);
    // console.log(addresArr);
    this.setData({
      region:addres.join('/'),
      historAddres:addresArr[2].code,
      show:false
    })
  },

  // 地址选择点击左上角取消
  cancel() {
    this.setData({
      show:false
    })
  },

  // 是否默认地址
  onChange({ detail }) {
    // 需要手动对 checked 状态进行更新
    this.setData({ checked: detail });
  },

  // 提交时表单内的value数据
  formSubmit(e) {
    let {value} = e.detail;
    Object.keys(value).forEach(item=>{
      item != 'switch' && ( value[item] = value[item].trim() );
    })

    let isEmpty = Object.keys(value).find(item=>{
      return item != 'switch' && value[item] == '';
    })
    if(isEmpty) {
      let name = {
        username:'收货人不能为空',
        phone:'请输入手机号码',
        region:'请选择所在地区',
        detailedAddres:'请填写详细地址',
      }
      Toast(name[isEmpty]);
      return;
    }

    if(!this.data.isCorrect) {
      Toast('请输入正确号码格式');
      return;
    }

    value.area = this.data.historAddres;
    value.id = this.data.id;

    this.changeMyAddres(value);
  },

  // 修改当前地址
  async changeMyAddres(addres) {
    // console.log(addres);
    let {errCode} = await changeAddress(addres);
    if(errCode == 0) {
      this.Backspace('修改成功');
    }else{
      this.Backspace('修改失败，请重试');
    }
  },

  // 返回上一页
  Backspace(message) {
    Toast(message);
    wx.navigateBack(); //返回上一页
  },

  // 删除当前地址
  deleteMyAddres() {
    let _this = this;
    Dialog.confirm({
      title: '确认删除当前地址',
    })
      .then( async () => {
        let id = _this.data.id;
        let {errCode} = await deleteAddress(id);
        if(errCode == 0) {
          _this.Backspace('删除成功');
        }else{
          _this.Backspace('删除失败，请重试');
        }
      })
      .catch(() => {
        // on cancel
      });

  },

    // 生命周期函数--监听页面加载
  onLoad: function (options) {
    // let myAddres = {
    //   address_detail: "城隍大道109号",
    //   address_id: 5,
    //   county_code: 130304,
    //   is_selected: 1,
    //   openid: "jj",
    //   region: "河北省/秦皇岛市/北戴河区",
    //   to_nm: "托雷鸡亚",
    //   to_phone: 17897845679
    // }
    let {myAddres} = options;
    myAddres = JSON.parse(myAddres);
    // console.log(myAddres);
    this.setData({
      id:myAddres.address_id,
      username:myAddres.to_nm,
      phone:myAddres.to_phone,
      region:myAddres.region,
      historAddres:myAddres.county_code,
      detailedAddres:myAddres.address_detail,
      checked:myAddres.is_selected == 1? true : false,
    })
  },

})